<?php
/**
 *
 	$o_serchcat::panel();

    $o_searchcat = new SearchCat(
		                           $category_id,
		                           $product_title,
		                           $cur_page,
		                           $item_per_page,
								   "id"
	                            );

    $o_searchcat->display();

 */

class SearchCat {

    //PUBLIC USE
	var $product_title = "";
    var $category_id = 0;
    var $cur_page = 1;
	var $item_per_page = 10;

    //PRIVATE USE
	var $categories = array();
	var $catID_list = "";
	var $product_where = "";
	var $limit_start = 0;
    var $total_products = 0;
	var $total_page = 0;
	var $av_col = array("id"=>"cn_ID", "my"=>"cn_MY");

	function __construct($category_id, $product_title, $cur_page, $item_per_page, $av_in = "") {

		if ( in_array($av_in, array_keys($this->av_col)) ) {
		    $this->product_where = "{$this->av_col[$av_in]}='y' AND ";			
		} else if ($av_in != "") {
            trigger_error("Please specify available country, it is either id or my or blank means both");
		}

		$this->category_id   = $category_id;
		$this->product_title = $product_title;
		$this->cur_page      = $cur_page;
		$this->item_per_page = $item_per_page;        
               
        $this->process();
	}

	function process() {

		$result = ($this->category_id)
				  ?
				  mysql_query("(SELECT ipc2.id, ipc2.title, ipc2.parent_id                          
								FROM {$GLOBALS['db']->product_category} as ipc2
								WHERE ipc2.id = {$this->category_id}
								LIMIT 1)
								UNION ALL
							   (SELECT ipc.id, ipc.title, ipc.parent_id                          
								FROM {$GLOBALS['db']->product_category} as ipc                           
								WHERE ipc.id != {$this->category_id}
								ORDER BY ipc.title ASC)")
				  :
				  mysql_query("SELECT ipc.id, ipc.title, ipc.parent_id                          
								   FROM {$GLOBALS['db']->product_category} as ipc                           
								   ORDER BY ipc.title ASC") ;

		//load all categories
		if(@mysql_num_rows($result)){
			while($myrow = mysql_fetch_row($result)) { 
				$names[$myrow[0]] = $myrow[1];
				$cats[$myrow[0]]  = $myrow[2]; 
			}
		}

		($this->category_id) 
		? 
		$this->display_options($this->hierarchize($cats, (int)$cats[$this->category_id]), $names, 0, $mylist) 
		: 
		$this->display_options($this->hierarchize($cats, 0, true), $names,0,$mylist);    

		$this->catID_list = implode(",", array_keys($this->categories));

		$this->product_where .= "catid IN ($this->catID_list)" . (($this->product_title!="") ? " AND (title LIKE '%{$this->product_title}%' or refno LIKE '%{$this->product_title}%')" : "");

		$this->total_products = $this->get_num_of_product();
		$this->total_page=ceil($this->total_products/$this->item_per_page);

		$this->page=($this->cur_page 
			         ? ($this->cur_page > $this->total_page
			            ? $this->total_page 
			            : ($this->cur_page<1? 1 
			         : $this->cur_page)) : 1);

		$this->limit_start=($this->page - 1) * $this->item_per_page;	
	}

	function display() {

        ob_start();

		$result = $this->get_product_tree_by_page();
		if(mysql_num_rows($result)!=0){
			echo 
			"<table class='prod-mini-list' id='tbl_searchresult'>
				<tr class='pml_header'>
					<td>".__("Ref No.")."</td>
					<td>".__("Title")."</td>
					<td>".__("Action")."</td>
				</tr>";

			while($myrow=mysql_fetch_row($result)){			

				$product = "";

				$refno = nhtmlentities($myrow[2]);
				$title = nhtmlentities($myrow[3]);
				$bv = number_format(calc_package_point("bv", $myrow[0]), 2);
				$dp = number_format(calc_package_point("dp", $myrow[0]), 2);
				$rp = number_format(calc_package_point("rp", $myrow[0]), 2);

				$product .= "
				<tr class='pml_body'>
					<td>{$refno}</td>
					<td>{$title} ({$bv}BV/DP{$dp}/CP{$rp})</td>
					<td><a href='#' rel=\"{$refno}\" name='add_prod'>Add</a></td
				</tr>";

				$products[] = array($myrow[1],$product);
			} mysql_free_result($result);	

			foreach ($this->categories as $id => $category) {

				$product_by_row = "";
				foreach ($products as $product) { if ($product[0] == $id) { $product_by_row .= $product[1];}}	  	    

				if ($product_by_row != "") {		 
					echo "
				<tr class='pml_cat'>
					<td colspan=3>$category</td>
				</tr>"; 
					echo $product_by_row;
			  }
			}

			echo "</table>";
			 
			echo "<p id='pml_pagelinks'>";
			foreach (range(1,$this->total_page) as $num) {
				echo " <a href='#'>{$num}</a> ";
			}        
			echo "</p>";

			$ajerrmsg = "1";
		}else{
			echo "<p class='red'>".__("No product found")."!</p>";
			$ajerrmsg = "2";
		}		

		echo "<br/>";

		return ob_get_clean();
	}

	function get_num_of_product() {
	  
	    $result = mysql_query("SELECT COUNT(id) 
                               FROM {$GLOBALS['db']->products}
                               WHERE {$this->product_where}
                               LIMIT 1") or die(mysql_error());  

        if ($myrow = mysql_fetch_row($result)) { return (int)$myrow[0]; }    
        return 0;                                                          
    }

    function hierarchize(&$cats, $parent,$found = false) {  	   

		$subs = array_keys($cats, $parent);  
		$tree = array();  
		foreach ($subs as $sub) {  
			if ($this->category_id == $sub || $found) { $tree[$sub] = $this->hierarchize($cats, $sub, true);}
		}  
		return count($tree) ? $tree : $parent;  
	}  
		   
	function display_options(&$tree, &$names, $nest=0, &$list) {  
			  
		foreach ($tree as $key => $branch) {  		  			    
			$list .= !empty($list) ? " > " .$names[$key] : $names[$key];	    
			$this->categories[$key] = $list;	    	    
			if (is_array($branch)) { 
			  $this->display_options($branch, $names, $nest + 1, $list); 		  	    
			} else { $list = "";}
		}  
	}  

	function get_product_tree_by_page() {

	    $result = mysql_query("SELECT 
	                             id, 
							     catid, 
							     refno, 
							     title,
								 bv,
								 dp,
								 rp
	                           FROM {$GLOBALS['db']->products}
                               WHERE {$this->product_where}
	                           ORDER BY FIND_IN_SET(catid,'{$this->catID_list}'), title ASC
	                           LIMIT {$this->limit_start}, {$this->item_per_page}") or die(mysql_error());
        return $result;	                        
    }

	static function panel($catid = 0, $product_title = "") {
        
        ob_start();

        if (!isset($GLOBALS['db'])) {
            trigger_error("Please assign \$db in global-level", E_USER_ERROR);
		}

        $r = mysql_query("select id,title from {$GLOBALS['db']->product_category}");

        echo "Category
              <select style='width:150px;' name='catid'><option value='0'>All</option>";

        while ($row = mysql_fetch_row($r)) {
	        echo "<option value='{$row[0]}'".(($catid == $row[0]) ? " selected" : "").">{$row[1]}</option>";
		}

		echo "</select>
                <input type='text' id='product_title' name='product_title' style=\"width:'100px'\" value=\"{$product_title}\"/>
                <input type='button' name='search_product' value=\"".__("Search")."\" /><br /><br />
	            <div id='searchresult'></div>";

        return ob_get_clean();
	}
}


?>